package cn.edu.scau.jds.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.time.LocalDate;
import java.time.Year;

/**
 * Created by junbin(seraphstorm@163.com) on 2016-01-26.
 */
@MappedTypes(value = Year.class)
@MappedJdbcTypes(value = JdbcType.DATE)
public class YearTypeHandler extends BaseTypeHandler<Year> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Year parameter, JdbcType jdbcType) throws SQLException {
        // 1、将Year转成LocalDate：获取该年第90天得到LocalDate
        LocalDate localDate = parameter.atDay(90);
        // 2、由于MySQL的year类型对应着java.sql.Date类型，所以我们直接setDate就可以了
        ps.setDate(i, Date.valueOf(localDate));
    }

    @Override
    public Year getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return transfer(rs.getDate(columnName));
    }

    @Override
    public Year getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return transfer(rs.getDate(columnIndex));
    }

    @Override
    public Year getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return transfer(cs.getDate(columnIndex));
    }

    private Year transfer(Date date) {
        // 1、将java.sql.Date转成LocalDate
        LocalDate localDate = date.toLocalDate();
        // 2、由LocalDate的year值静态生成Year
        return Year.of(localDate.getYear());
    }

}
